package cn.steel.controller;

import cn.steel.domain.entity.InventoryAnalysis;
import cn.steel.domain.entity.PriceTrendAnalysis;
import cn.steel.domain.entity.SupplierInfo;
import cn.steel.service.DashboardService;
import cn.steel.service.SupplierInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequiredArgsConstructor
public class DashboardController {
    private final SupplierInfoService supplierInfoService;
    private final DashboardService dashboardService;

    @ApiOperation("首页")
    @GetMapping("/")
    public String home(Model model) {
        // 获取供应商排行榜
        List<SupplierInfo> topSuppliers = supplierInfoService.getTop10Suppliers();
        log.info("加载首页，获取供应商排行榜: 数量={}", topSuppliers != null ? topSuppliers.size() : 0);
        model.addAttribute("suppliers", topSuppliers);

        // 获取库存分析数据
        List<InventoryAnalysis> category1Data = dashboardService.getInventoryDataByCategoryAndRegion(1L);
        List<InventoryAnalysis> category2Data = dashboardService.getInventoryDataByCategoryAndRegion(2L);
        List<InventoryAnalysis> category3Data = dashboardService.getInventoryDataByCategoryAndRegion(3L);
        model.addAttribute("category1Data", category1Data);
        model.addAttribute("category2Data", category2Data);
        model.addAttribute("category3Data", category3Data);
        log.info("category1Data: {}", category1Data);
        log.info("category2Data: {}", category2Data);
        log.info("category3Data: {}", category3Data);

        // 获取价格趋势数据
        List<PriceTrendAnalysis> priceTrend1Data = dashboardService.getPriceTrendsByCategory(1L);
        List<PriceTrendAnalysis> priceTrend2Data = dashboardService.getPriceTrendsByCategory(2L);
        List<PriceTrendAnalysis> priceTrend3Data = dashboardService.getPriceTrendsByCategory(3L);
        model.addAttribute("priceTrend1Data", priceTrend1Data != null ? priceTrend1Data : new ArrayList<>());
        model.addAttribute("priceTrend2Data", priceTrend2Data != null ? priceTrend2Data : new ArrayList<>());
        model.addAttribute("priceTrend3Data", priceTrend3Data != null ? priceTrend3Data : new ArrayList<>());
        log.info("priceTrend1Data: {}", priceTrend1Data);
        log.info("priceTrend2Data: {}", priceTrend2Data);
        log.info("priceTrend3Data: {}", priceTrend3Data);

        //检查用户是否为游客
        String userType = (String) model.getAttribute("userType");
        boolean isGuest = "guest".equals(userType);
        model.addAttribute("isGuest", isGuest);
        return "analysis";
    }
}